package cn.cvs.controller;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SupplierService;
import cn.cvs.utils.Constants;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("supplier")
public class SupplierController {

    Logger logger = Logger.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;

    @GetMapping(value = {"/simpleList"},produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object getSupplierList() {
        List simpleList = null;
        try {
            simpleList = this.supplierService.getList();
        } catch (Exception var3) {
            var3.printStackTrace();
        }
        return JSONArray.toJSONString(simpleList);  //toJSONString
    }

    @RequestMapping(value = "list")
    public String getSupplierList(Model model, @RequestParam(value = "querySupName", required = false) String querySupName, @RequestParam(value = "querySupCode", required = false) String querySupCode, @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex) {
        List<Supplier> suppList = null;
        try {

            PageHelper.startPage(pageIndex, 5);
            //总数量(表)
            /* int totalCount=supplierService.getCount(querySupName,querySupCode);*/
            //总页数
            suppList = supplierService.getList(querySupName, querySupCode);
            PageInfo<Supplier> pageInfo = new PageInfo<>(suppList);
            model.addAttribute("supplierList", suppList);
            model.addAttribute("querySupName", querySupName);
            model.addAttribute("querySupCode", querySupCode);
            model.addAttribute("page", pageInfo);
            return "supplier/list";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/user/toSysError";
        }
    }

    //跳转到添加用户页面
    @GetMapping({"/toAdd"})
    public String addUser() {
        return "supplier/add";
    }

    @PostMapping("/add")
    public String addSupplier(Supplier supplier, HttpSession session, HttpServletRequest request,
                              @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) throws Exception {
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        System.out.println("文件路径: ============== > " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];//取到单个文件
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                System.out.println("原文件名:" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);
                System.out.println("后缀:" + prefix);
                int filesize = 500000;
                System.out.println("文件大小>>>>>" + filesize);
                if (attach.getSize() > filesize) //上传大小不得超过500kb
                {
                    request.setAttribute(errorInfo, "*上传大小不得超过500kb");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pnge")) {
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    System.out.println("新的文件名:" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, "* 上传失败");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        orgCodePicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    System.out.println(">>>>>>>>companyLicPicPath" + companyLicPicPath);
                    System.out.println(">>>>>>>>orgCodePicPath" + orgCodePicPath);
                } else {
                    request.setAttribute(errorInfo, "* 上传图片格式不正确");
                    flag = false;
                }
            }
        }

        if (flag) {
            supplier.setCreatedUserId(((SysUser) request.getSession().getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCompanyLicPicPath(companyLicPicPath);
            supplier.setOrgCodePicPath(orgCodePicPath);
            int count = supplierService.add(supplier);
            if (count > 0) {
                return "redirect:/supplier/list";
            }
        }
        return "supplier/add";
    }

    @GetMapping({"/view/{id}"})
    public String view(@PathVariable Integer id, Model model, HttpServletRequest request) throws Exception {
        this.logger.debug("view id===================== " + id);
        Supplier supplier = this.supplierService.getById(id);
        String[] paths;
        if (supplier.getCompanyLicPicPath() != null && !"".equals(supplier.getCompanyLicPicPath())) {
            paths = supplier.getCompanyLicPicPath().split("\\" + File.separator);
            this.logger.debug("view companyLicPicPath paths[paths.length-1]============ " + paths[paths.length - 1]);
            supplier.setCompanyLicPicPath(request.getContextPath() + "/statics/uploadfiles/" + paths[paths.length - 1]);
        }

        if (supplier.getOrgCodePicPath() != null && !"".equals(supplier.getOrgCodePicPath())) {
            paths = supplier.getOrgCodePicPath().split("\\" + File.separator);
            this.logger.debug("view orgCodePicPath paths[paths.length-1]============ " + paths[paths.length - 1]);
            supplier.setOrgCodePicPath(request.getContextPath() + "/statics/uploadfiles/" + paths[paths.length - 1]);
        }

        model.addAttribute(supplier);
        return "supplier/view";
    }


    @ResponseBody
    @GetMapping({"/{id}/view"})
    public Object view(@PathVariable Integer id) throws Exception {
        System.out.println("根据id查询用户详情id:" + id);
        Supplier supplier = null;
        supplier = this.supplierService.getById(id);
        System.out.println("查询到用户信息：" + supplier);
        return supplier;
    }

    @GetMapping({"/toUpdate/{id}"})
    public String toUpdate(@PathVariable Integer id, Model model) throws Exception {
        Supplier supplier = this.supplierService.getById(id);
        model.addAttribute(supplier);
        return "supplier/update";
    }

    @PostMapping({"/update"})
    public String update(Supplier supplier, HttpSession session) throws Exception {
        this.logger.debug("修改供货商信息supplier:" + supplier);
        supplier.setCreatedUserId(((SysUser)session.getAttribute("userSession")).getId());
        return this.supplierService.update(supplier) ? "redirect:/supplier/list" : "supplier/update";
    }

    @DeleteMapping({"/del/{id}"})
    @ResponseBody  //  作用：将方法的返回值，以特定的格式写入到response的body区域，进而将数据返回给客户端。
    public Object del(@PathVariable(value = "id",required = false) Integer id) throws Exception //PathVariable获取URL中路径的参数值
    {
        HashMap resultMap = new HashMap();
        int count=supplierService.deleteById(id);
        try {
            if (count>0) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return JSONArray.toJSONString(resultMap);
    }
}